const common = require("../../../common/common.js").common;

const addressParse = require("address-parse.js");

Page({
    /**
   * 页面的初始数据
   */
    data: {
        wwb: 0,
        streetName: "",
        wwb_street_id: "",
        wwb_street: "",
        cityA: [],
        streetA: [],
        isOld: false,
        position: "",
        formConfig: [ {
            formType: 1,
            formData: {
                title: "收件人",
                placeholder: "请填写收件人姓名",
                important: true,
                name: "name"
            },
            formStyle: {
                borderRadius: "8rpx 8rpx 0 0"
            }
        }, {
            formType: 1,
            formData: {
                title: "手机号",
                placeholder: "请填写收件人手机号",
                important: true,
                name: "phone",
                maxlength: 11,
                type: "number"
            },
            formStyle: {}
        }, {
            formType: 5,
            formData: {
                title: "定位",
                placeholder: "请选择定位的地址",
                important: true,
                name: "position"
            },
            formStyle: {}
        }, {
            formType: 2,
            formData: {
                title: "所在地区",
                mode: "region",
                important: true,
                name: "city",
                value: []
            },
            formStyle: {}
        }, {
            formType: 6,
            formData: {
                title: "街道",
                mode: "",
                important: false,
                name: "street",
                value: "",
                street: ""
            },
            formStyle: {}
        }, {
            formType: 3,
            formData: {
                title: "详细地址",
                mode: "region",
                important: true,
                placeholder: "请填写详细地址",
                name: "area"
            },
            formStyle: {
                borderRadius: "0 0 8rpx 8rpx"
            }
        }, {
            formType: 4,
            formData: {
                title: "设为默认地址",
                name: "def",
                checked: true,
                value: true
            },
            formStyle: {
                marginTop: "20rpx",
                borderRadius: "8rpx"
            }
        } ]
    },
    /**
   * 验证表单
   */
    form(e) {
        let that = this;
        var formValue = e.detail.value;
        var formConfig = that.data.formConfig;
        if (formConfig.length > 0) {
            for (var i = 0; i < formConfig.length; i++) {
                //处理数组
                if (formValue[formConfig[i].formData.name] instanceof Array) {
                    formValue[formConfig[i].formData.name] = formValue[formConfig[i].formData.name].join("-");
                }
                var reg2 = /^[1][0-9][0-9]{9}$/;
                if (formConfig[i].formData.name == "phone" && !reg2.test(formConfig[i].formData.value)) {
                    wx.showModal({
                        title: "提示",
                        content: "请输入正确的手机号码！",
                        showCancel: false
                    });
                    return false;
                }
                if (formConfig[i].formType == 4) {
                    formValue[formConfig[i].formData.name] = formValue[formConfig[i].formData.name] ? 1 : 0;
                }
                //找出必填项
                                var important = formConfig[i].formData.important == true ? true : false;
                //console.log(important, formConfig[i].formData.important)
                                if (important) {
                    //判断有没有值
                    var formItemValue = formValue[formConfig[i].formData.name];
                    console.log(formItemValue);
                    if (!formItemValue || formItemValue.length == 0) {
                        //有值
                        wx.showToast({
                            icon: "none",
                            title: formConfig[i].formData.title + "不能为空"
                        });
                        return false;
                    }
                }
            }
        }
        that.saveAddress(formValue);
    },
    /**
   * 保存地址
   */
    saveAddress(data) {
        let that = this;
        var doStr = that.data.isOld ? "edit" : "new";
        var id = that.data.id;
        common.request({
            endpoint: "My/myinfo/address_save",
            data: {
                ...data,
                position: that.data.formConfig[2].formData.value,
                do: doStr,
                id: id,
                wwb_street: that.data.wwb_street,
                wwb_street_id: that.data.wwb_street_id
            },
            method: "post",
            success(res) {
                console.log(res);
                wx.showToast({
                    title: "保存成功",
                    icon: "none",
                    success() {
                        //返回前一页
                        wx.navigateBack({});
                    }
                });
            }
        });
    },
    //全局基础配置信息
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                var features = common.getModulesSwich(res.extra.features);
                //处理数据格式
                                that.setData({
                    wwb: features.wwb
                });
            }
        });
    },
    updateValue(e) {
        var formConfig = this.data.formConfig;
        var field = e.detail.field;
        formConfig.forEach((item, index) => {
            if (item.formData.name == field) {
                item.formData.value = e.detail.value;
                if (item.formType == 2) {
                    this.setData({
                        cityA: e.detail.value,
                        streetName: "",
                        wwb_street: "",
                        wwb_street_id: ""
                    });
                    this.getStreet();
                }
                if (item.formType == 4) {
                    item.formData.checked = e.detail.value;
                }
                if (item.formType == 5) {
                    console.log(e.detail);
                    this.setData({
                        position: e.detail.position
                    });
                    this.setData({
                        ["formConfig[2].formData.value"]: e.detail.position
                    });
                }
                if (item.formType == 6) {
                    console.log(22);
                    console.log(this.data.streetA[e.detail.value]);
                    this.setData({
                        wwb_street_id: this.data.streetA[e.detail.value].id || "",
                        wwb_street: this.data.streetA[e.detail.value].name || ""
                    });
                }
                this.setData({
                    formConfig: formConfig
                });
            }
        });
        // this.setData({
        //   formConfig
        // })
        },
    //自动填充
    identifyaddress: function(a) {
        this.setData({
            addridentifyloading: !0
        }), wx.showLoading({
            title: "请稍候..."
        });
        var e = this;
        i.identifyAddress(a, function(a) {
            e.setData({
                addridentifyloading: !1
            }), null != a && (a.success ? e.setData(a) : a.tele && a.tele.length > 0 && e.setData({
                name: a.name,
                tele: a.tele,
                addr: a.addr
            })), e.setData({
                addridentifyloading: !1
            }), wx.hideLoading();
        });
    },
    // addressIdentify: function (a) {
    //   if (!this.data.addridentifyloading) {
    //     var e = this.data.addridentify;
    //     console.log(e)
    //     null != e && null != e && "" != e.trim() ? this.identifyaddress(e) : console.log("请输入内容");
    //   }
    // },
    addressIdentify: function() {
        let that = this;
        var e = that.data.addridentify;
        console.log("e", e);
        let parse_list = addressParse.parse(e);
        console.log("parse_list", parse_list);
        var formConfig = that.data.formConfig;
        formConfig.forEach((item, index) => {
            switch (item.formData.name) {
              case "name":
                item.formData.value = parse_list.name;
                break;

              case "phone":
                item.formData.value = parse_list.mobile;
                break;

              case "city":
                item.formData.value = [ parse_list.province, parse_list.city, parse_list.area ];
                item.formData.checked = [ parse_list.province, parse_list.city, parse_list.area ];
                that.setData({
                    cityA: [ parse_list.province, parse_list.city, parse_list.area ]
                });
                break;

              case "area":
                item.formData.value = parse_list.addr;
                break;
            }
        });
        that.setData({
            formConfig: formConfig
        });
        that.getStreet();
    },
    addrInput: function(a) {
        var e = a.currentTarget.dataset.name;
        this.data[e] = a.detail.value;
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        wx.hideShareMenu();
        let that = this;
        var formConfig = that.data.formConfig;
        //query里有地址
                if (options.address) {
            var addressInfo = JSON.parse(options.address);
            formConfig.forEach((item, index) => {
                item.formData.value = addressInfo[item.formData.name];
                if (item.formType == 4) {
                    item.formData.checked = addressInfo[item.formData.name];
                }
            });
            that.setData({
                formConfig: formConfig,
                cityA: addressInfo.city,
                streetName: addressInfo.wwb_street,
                wwb_street: addressInfo.wwb_street,
                wwb_street_id: addressInfo.wwb_street_id
            });
            this.getStreet();
            //query里有old
                        if (options.old) {
                that.setData({
                    isOld: true,
                    id: addressInfo.id
                });
            }
        }
        this.getBase();
    },
    getStreet() {
        let that = this;
        console.log(that.data.cityA);
        common.request({
            endpoint: "Wwb/index/street-list",
            data: {
                province: that.data.cityA[0] || "",
                city: that.data.cityA[1] || "",
                area: that.data.cityA[2] || ""
            },
            method: "post",
            success(res) {
                let arr = res.extra;
                that.setData({
                    streetA: res.extra
                });
            }
        });
    },
    chooseAddress: function() {
        let that = this;
        wx.chooseLocation({
            success(res) {
                var name = res.name;
                var formConfig = that.data.formConfig;
                formConfig.forEach((item, index) => {
                    if (item.formData.name == "position") {
                        item.formData.value = name;
                        this.setData({
                            formConfig: formConfig
                        });
                    }
                });
                var key = "formData";
                that.setData({
                    ["formData"]: res.name,
                    latitude: res.latitude,
                    longitude: res.longitude
                });
            },
            fail: function() {
                wx.getSetting({
                    success: function(res) {
                        var statu = res.authSetting;
                        if (!statu["scope.userLocation"]) {
                            wx.showModal({
                                title: "是否授权当前位置",
                                content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
                                success: function(tip) {
                                    if (tip.confirm) {
                                        wx.openSetting({
                                            success: function(data) {
                                                if (data.authSetting["scope.userLocation"] === true) {
                                                    wx.showToast({
                                                        title: "授权成功",
                                                        icon: "success",
                                                        duration: 1e3
                                                    });
                                                    //授权成功之后，再调用chooseLocation选择地方
                                                                                                        that.chooseAddress();
                                                } else {
                                                    wx.showToast({
                                                        title: "授权失败",
                                                        icon: "success",
                                                        duration: 1e3
                                                    });
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    },
                    fail: function(res) {
                        wx.showToast({
                            title: "调用授权窗口失败",
                            icon: "success",
                            duration: 1e3
                        });
                    }
                });
            }
        });
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {}
});